package mdb

import (
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"strings"
	"time"
)

type DB struct {
	*mgo.Session
}

type BaseMgoPO struct {
	ID         bson.ObjectId `bson:"_id,omitempty"`
	CreateTime string        `bson:"create_time"`
	UpdateTime string        `bson:"update_time"`
	Delete     bool          `bson:"is_delete"` // 是否删除
}

func New(c Config, opts ...Option) (*DB, error) {
	o := NewOptions(opts...)

	mongoDb, err := newMongoDB(c, o)

	if err != nil {
		return nil, err
	}
	return &DB{Session: mongoDb}, nil
}

func (m *DB) Health() bool {
	return true
}

func newMongoDB(c Config, opts Options) (*mgo.Session, error) {
	mongoDBDialInfo := &mgo.DialInfo{
		Addrs:    strings.Split(c.Hosts, ","),
		Timeout:  60 * time.Second,
		Database: c.AuthDb,
		Username: c.AuthUser,
		Password: c.AuthPass,
	}
	session, err := mgo.DialWithInfo(mongoDBDialInfo)
	if err != nil {
		panic(`mongo initDb: data(` + c.Hosts + `): ` + err.Error())
	}
	session.SetPoolLimit(opts.MaxPoolSize)
	session.SetMode(mgo.Monotonic, true)
	return session, nil
}
